package com.indexingsystem.system.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.indexingsystem.boss.Vo.ExportInstitutionListByIdVo;
import com.indexingsystem.boss.Vo.InstitutionsInfoVo;
import com.indexingsystem.boss.Vo.InstitutionsListVo;
import com.indexingsystem.boss.Vo.InstitutionsVo;
import com.indexingsystem.boss.Vo.OrderCanelReqVo;
import com.indexingsystem.boss.Vo.OrderPublishVo;
import com.indexingsystem.boss.Vo.QueryInstitutionsVo;
import com.indexingsystem.boss.Vo.StatusList;
import com.indexingsystem.boss.Vo.TreeQueryVo;
import com.indexingsystem.boss.admin.mapper.InstitutionsMapper;
import com.indexingsystem.boss.admin.mapper.IprulesMapper;
import com.indexingsystem.boss.admin.mapper.PusersMapper;
import com.indexingsystem.boss.admin.mapper.ResourceTypeMapper;
import com.indexingsystem.boss.admin.mapper.ResourcesMapper;
import com.indexingsystem.boss.admin.mapper.RoleGroupsMapper;
import com.indexingsystem.boss.admin.mapper.RolesMapper;
import com.indexingsystem.boss.admin.mapper.TerminalsMapper;
import com.indexingsystem.boss.admin.mapper.UserInfosMapper;
import com.indexingsystem.boss.admin.mapper.UserInstitutionMapper;
import com.indexingsystem.boss.admin.mapper.UserRoleMapper;
import com.indexingsystem.boss.common.ChineseCharToEnUtil;
import com.indexingsystem.boss.common.PagedResult;
import com.indexingsystem.boss.entity.AnalysisList;
import com.indexingsystem.boss.entity.AppInstitutionRelations;
import com.indexingsystem.boss.entity.Applications;
import com.indexingsystem.boss.entity.ArticleContents;
import com.indexingsystem.boss.entity.Articles;
import com.indexingsystem.boss.entity.AuditLogs;
import com.indexingsystem.boss.entity.Books;
import com.indexingsystem.boss.entity.Games;
import com.indexingsystem.boss.entity.Institutions;
import com.indexingsystem.boss.entity.Iprules;
import com.indexingsystem.boss.entity.Magazines;
import com.indexingsystem.boss.entity.OftenConsignees;
import com.indexingsystem.boss.entity.OrderProcesses;
import com.indexingsystem.boss.entity.OrderProducts;
import com.indexingsystem.boss.entity.OrderResourceProductsDetail;
import com.indexingsystem.boss.entity.OrderResoursePrice;
import com.indexingsystem.boss.entity.Orders;
import com.indexingsystem.boss.entity.Pusers;
import com.indexingsystem.boss.entity.ResCategoryRelations;
import com.indexingsystem.boss.entity.ResourceCategors;
import com.indexingsystem.boss.entity.ResourceRelations;
import com.indexingsystem.boss.entity.ResourceType;
import com.indexingsystem.boss.entity.Resources;
import com.indexingsystem.boss.entity.RoleGroups;
import com.indexingsystem.boss.entity.Roles;
import com.indexingsystem.boss.entity.SpecialResourceDatas;
import com.indexingsystem.boss.entity.Terminals;
import com.indexingsystem.boss.entity.UserInfos;
import com.indexingsystem.boss.entity.UserInstitution;
import com.indexingsystem.boss.entity.UserRole;
import com.indexingsystem.boss.entity.Videos;
import com.indexingsystem.boss.logback.LogCvt;
import com.indexingsystem.boss.utils.BeanUtils;
import com.indexingsystem.boss.utils.DateUtil;
import com.indexingsystem.boss.utils.FileManipulationTool;
import com.indexingsystem.boss.utils.InstitutionLoadUtils;
import com.indexingsystem.boss.utils.JsonUtil;
import com.indexingsystem.boss.utils.VideoCopyFileUtils;
import com.indexingsystem.db.mongoDB.impl.InstitutionsMongo;
import com.indexingsystem.db.mongoDB.impl.UserPublishMongo;
import com.indexingsystem.db.mongoDB.po.UserPublishMongoVo;
import com.indexingsystem.db.redis.InstitutionsRedis;
import com.indexingsystem.system.service.IAnalysisListService;
import com.indexingsystem.system.service.IAppInstitutionRelationsService;
/*import com.indexingsystem.system.service.IApplicationsService;*/
import com.indexingsystem.system.service.IArticlesService;
import com.indexingsystem.system.service.IAuditLogsService;
import com.indexingsystem.system.service.IBooksService;
import com.indexingsystem.system.service.IGamesService;
import com.indexingsystem.system.service.IMagazinesService;
import com.indexingsystem.system.service.IVideosService;
import com.indexingsystem.system.service.InstitutionsService;
import com.indexingsystem.system.task.ExportInstitutionList;

@Service
public class InstitutionsServiceImpl implements InstitutionsService {

	@Resource
	private InstitutionsMapper					institutionsMapper;

	@Resource
	private PusersMapper						pusersMapper;

	@Resource
	private UserInfosMapper						userInfosMapper;

	@Resource
	private UserInstitutionMapper				userInstitutionMapper;

	@Resource
	private UserRoleMapper						userRoleMapper;

	@Resource
	private RolesMapper							rolesMapper;

	@Resource
	private RoleGroupsMapper					roleGroupsMapper;

	@Resource
	private TerminalsMapper						terminalsMapper;

	@Resource
	private IprulesMapper						iprulesMapper;

	@Resource
	private ResourceTypeMapper					resourceTypeMapper;


	/*@Resource
	private IApplicationsService				iApplicationsService;
*/
	@Resource
	private IAppInstitutionRelationsService		appInstitutionRelationsService;

	@Resource
	private IAnalysisListService				analysisListService;

	@Resource
	private ResourcesMapper						resourcesMapper;

	@Resource
	private IBooksService						iBooksService;
	@Resource
	private IVideosService						iVideosService;
	@Resource
	private IGamesService						iGamesService;
	@Resource
	private IArticlesService					iArticlesService;
	@Resource
	private IMagazinesService					iMagazinesService;

	@Resource
	private IAuditLogsService					auditLogsService;

	@Override
	public int deleteByPrimaryKey(String institutionId) {
		return institutionsMapper.deleteByPrimaryKey( institutionId );
	}

	@Override
	public int insertSelective(Institutions record) {
		int result = 0;
		result += institutionsMapper.insertSelective( record );
		List<InstitutionsListVo> institutionsListVo = null;
		institutionsListVo = InstitutionsMongo.findInstitutionsAll( new HashMap<String, Object>() );
		if (null != institutionsListVo && institutionsListVo.size() > 0) {
			// 先删除mongo数据
			InstitutionsMongo.deleteInstitutionsAll();
		}
		institutionsListVo = institutionsMapper.getInstitutionsList();
		if (null != institutionsListVo && institutionsListVo.size() > 0) {
			// 存储mogoDb
			InstitutionsMongo.addInstitutions( institutionsListVo );
		}

		return result;
	}

	@Override
	public Institutions selectByPrimaryKey(String institutionId) {
		return institutionsMapper.selectByPrimaryKey( institutionId );
	}

	/**
	 * 获取已到期并且已禁用机构.
	 * 
	 * @param institutionIdList
	 * @return
	 */
	@Override
	public List<InstitutionsInfoVo> getInstitutionsByValidDateIsDelte(List<String> institutionIdList) {
		return institutionsMapper.getInstitutionsByValidDateIsDelte( institutionIdList );
	}

	/**
	 * 通过机构id获取机构信息.
	 * 
	 * @param institutionId
	 * @return
	 */
	@Override
	public Map<String, String> selectByInstitutionId(String institutionId) throws Exception {
		Map<String, String> institutionMap = InstitutionsRedis.getAll_digitalhome_institutions_institutions_id( institutionId );
		LogCvt.info( "redis获取机构信息查询为空，从mysql查询机构信息，查询条件：institutionId:" + institutionId );
		Institutions institutions = institutionsMapper.selectByPrimaryKey( institutionId );
		try {
			LogCvt.info( "redis获取机构信息查询为空，重新设置缓存" );
			InstitutionsRedis.set_digitalhome_institutions_institutions_id( institutions );
		} catch (Exception e) {
			LogCvt.error( "Common设置机构信息缓存失败, 原因:" + e.getMessage(), e );
		}
		institutionMap = InstitutionsRedis.getAll_digitalhome_institutions_institutions_id( institutionId );
		return institutionMap;
	}

	@Override
	public int updateByPrimaryKeySelective(Institutions record) {
		return institutionsMapper.updateByPrimaryKeySelective( record );
	}

	@Override
	public List<InstitutionsVo> selectBindUser(String institutionId) {
		return institutionsMapper.selectBindUser( institutionId );
	}

	@Override
	public PagedResult<Institutions> selectInstitutionsList(Integer pageNo, Integer pageSize) {
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? 10 : pageSize;
		// startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		PageHelper.startPage( pageNo, pageSize );
		return BeanUtils.toPagedResult( institutionsMapper.selectInstitutionsList() );
	}

	/**
	 * 通过机构id导出离线升级包.
	 * 
	 * @param institutionId
	 */
	@Override
	public String exportInstitutionsListById(String institutionId) {
		Set<String> institutionIdSet = null;//
		List<Institutions> institutionsList = null;
		List<Pusers> pusersList = null;
		List<String> userIdList = null;
		List<UserInfos> userInfosList = null;
		List<UserInstitution> userInstitutionList = null;
		List<UserRole> userRoleList = null;
		List<String> roleIdList = null;//
		List<Roles> rolesList = null;
		List<String> roleGroupIdList = null;
		List<RoleGroups> roleGroupsList = null;
		List<Terminals> terminalsList = null;
		List<Iprules> iprulesList = null;
		List<String> orderNoList = null;//
		OrderPublishVo orderPublishVo = null;//
		// List<ApplicationPlatformVo> analysisiByInstitionList = null;

		Orders orders = null;
		List<Orders> orderList = null;
		List<OrderProducts> orderProductsList = null;
		List<OrderProducts> orderProductsListObj = null;
		OftenConsignees oftenConsignees = null;
		List<OftenConsignees> oftenConsigneesList = null;
		List<OrderProcesses> orderProcessesList = null;
		List<OrderProcesses> orderProcessesListObj = null;
		List<ResourceCategors> resourceCategorysList = null;
		List<ResourceCategors> resourceCategorysListObj = null;
		List<Resources> resourcesList = null;
		List<Resources> resourcesListObj = null;
		List<ResourceRelations> resourceRelationsList = null;
		List<ResourceRelations> resourceRelationsListObj = null;
		List<ResCategoryRelations> resCategoryRelationsList = null;
		List<ResCategoryRelations> resCategoryRelationsListObj = null;
		List<ArticleContents> articleContentsList = null;
		List<ArticleContents> articleContentsListObj = null;
		List<Articles> articlesList = null;
		List<Articles> articlesListObj = null;
		List<Books> booksList = null;
		List<Books> booksListObj = null;
		List<Games> gamesList = null;
		List<Games> gamesListObj = null;
		List<Videos> videosList = null;
		List<Videos> videosListObj = null;
		List<Magazines> magazinesList = null;
		List<Magazines> magazinesListObj = null;
		List<SpecialResourceDatas> specialResourceDatasList = null;
		List<SpecialResourceDatas> specialResourceDatasListObj = null;
		List<ResourceType> resourceTypeList = null;
		List<ResourceType> resourceTypeListObj = null;
		OrderCanelReqVo orderCanelReqList = null;
		List<OrderCanelReqVo> orderCanelReqListObj = null;
		List<OrderResourceProductsDetail> orderResourceProductsDetailsList = null;
		List<OrderResourceProductsDetail> orderResourceProductsDetailsListObj = null;
		List<OrderResoursePrice> orderResoursePriceList = null;
		List<OrderResoursePrice> orderResoursePriceListObj = null;
		AuditLogs auditLog = null;
		List<AuditLogs> auditLogsList = null;

		String filePath = null;
		try {
			// 1、机构信息离线数据包:全量升级
			if (!institutionId.equals( InstitutionLoadUtils.getString( "institutionId" ))) {
				institutionIdSet = getPublishInstitutionsTreeList( institutionId );
				LogCvt.info( new StringBuffer( "机构用户离线数据包导出开始:institutionIdSet " ).append( JsonUtil.obj2Json( institutionIdSet ) ).toString() );
				Institutions institutionsObj = null;
				if (null != institutionIdSet && institutionIdSet.size() > 0) {
					institutionsList = new ArrayList<Institutions>();
					for (String institutionIdVal : institutionIdSet) {
						institutionsObj = selectByPrimaryKey( institutionIdVal );
						if (null != institutionsObj) {
							if (!institutionsList.contains( institutionsObj )) {
								institutionsList.add( institutionsObj );
							}
						}

					}
				}

				// 通过机构id获取用户userId，通过用户userId查询mongo缓存用户信息，如果用户不存在，查询db，缓存mongo
				List<String> mongoUserIdList = null;
				List<UserInstitution> queryUserInstitutionList = userInstitutionMapper.getUserInstitutionsListByInstitutionId( institutionId );
				if (null != queryUserInstitutionList && queryUserInstitutionList.size() > 0) {
					mongoUserIdList = new ArrayList<String>();
					for (UserInstitution userInstitution : queryUserInstitutionList) {
						if (!mongoUserIdList.contains( userInstitution.getUserId() )) {
							mongoUserIdList.add( userInstitution.getUserId() );
						}
					}
				}
				
				//存储用户信息
				List<Pusers> officPusersList = null;
				List<UserInfos> officUserInfosList = null;
				List<UserInstitution> officUserInstitutionList = null;
				List<UserRole> officUserRoleList = null;
				List<Roles> officRolesList = null;
				List<RoleGroups> officRoleGroupsList = null;
				if (null != mongoUserIdList && mongoUserIdList.size() > 0) {
					officPusersList = new ArrayList<Pusers>();
					officUserInfosList = new ArrayList<UserInfos>();
					officUserInstitutionList = new ArrayList<UserInstitution>();
					officUserRoleList= new ArrayList<UserRole>();
					officRolesList = new ArrayList<Roles>();
					officRoleGroupsList = new ArrayList<RoleGroups>();					
					for (String userIdVal : mongoUserIdList) {
						// 通过userId获取mongo用户信息
						UserPublishMongoVo userPublishMongoVo = UserPublishMongo.selectUserInfoByUserId( userIdVal );
						Pusers targetPuser = null;
						UserInfos targetUserInfos = null;
						UserInstitution targetUserInstitution = null;
						UserRole targetUserRole = null;
						Roles targetRoles = null;
						RoleGroups targetRoleGroups = null;
						if (null != userPublishMongoVo) {
							targetPuser = userPublishMongoVo.getPusers();
							targetUserInfos = userPublishMongoVo.getUserInfos();
							targetUserInstitution = userPublishMongoVo.getUserInstitution();
							targetUserRole = userPublishMongoVo.getUserRoleList().get( 0 );
							targetRoles = userPublishMongoVo.getRolesList().get( 0 );
							targetRoleGroups = userPublishMongoVo.getRoleGroupsList().get( 0 );
						} else {

							Pusers queryPusers = pusersMapper.selectPusersInfoList( userIdVal );
							// 获取用户信息
							targetPuser = queryPusers;

							// 获取用户详情信息
							UserInfos userInfose = userInfosMapper.selectUserInfoByUserIdVo( userIdVal );
							targetUserInfos = userInfose;
							// 获取用户机构信息
							UserInstitution userInstitutions = userInstitutionMapper.selectUserInstitutionByUserId( userIdVal );
							targetUserInstitution = userInstitutions;

							// 获取用户角色信息
							UserRole userRoles = userRoleMapper.selectByPrimaryUserId( userIdVal );
							targetUserRole = userRoles;

							// 用户的角色信息
							Roles roles = rolesMapper.selectByPrimaryKey( userRoles.getRoleId() );
							targetRoles = roles;

							// 角色组相关信息
							RoleGroups roleGroups = roleGroupsMapper.selectByPrimaryKey( roles.getRoleGroupId() );
							targetRoleGroups = roleGroups;

							// 缓存mongo 用户信息
							UserPublishMongoVo targetUserPublishMongoVo = new UserPublishMongoVo();
							targetUserPublishMongoVo.setUserId( userIdVal );
							targetUserPublishMongoVo.setPusers( targetPuser );
							targetUserPublishMongoVo.setUserInfos( targetUserInfos );
							targetUserPublishMongoVo.setUserInstitution( targetUserInstitution );

							List<UserRole> userRolesList = new ArrayList<UserRole>();
							userRolesList.add( targetUserRole );
							targetUserPublishMongoVo.setUserRoleList( userRolesList );

							// 4、获取角色信息列表
							List<Roles> mongoRolesList = new ArrayList<Roles>();

							// 5、角色组列表
							List<RoleGroups> mongoRoleGroupsList = new ArrayList<RoleGroups>();
							if (null != userRolesList && userRolesList.size() > 0) {
								for (UserRole userRoleVal : userRolesList) {
									Roles queryRoles = rolesMapper.selectByPrimaryKey( userRoleVal.getRoleId() );
									if (null != queryRoles) {
										if (!mongoRolesList.contains( queryRoles )) {
											mongoRolesList.add( queryRoles );
										}

										RoleGroups queryRoleGroups = roleGroupsMapper.selectByPrimaryKey( queryRoles.getRoleGroupId() );
										if (null != queryRoleGroups) {
											if (!mongoRoleGroupsList.contains( queryRoleGroups )) {
												mongoRoleGroupsList.add( queryRoleGroups );
											}
										}
									}
								}
							}

							targetUserPublishMongoVo.setRolesList( mongoRolesList );
							targetUserPublishMongoVo.setRoleGroupsList( mongoRoleGroupsList );
							try {
								if (null != targetUserPublishMongoVo) {
									UserPublishMongo.addUser( targetUserPublishMongoVo );
								}
							} catch (Exception ex) {
								LogCvt.error( ex.getMessage(), ex );
							}

						}
						
						if(!officPusersList.contains( targetPuser )){
							officPusersList.add( targetPuser );
						}
						if(!officUserInfosList.contains( targetUserInfos )){
							officUserInfosList.add( targetUserInfos );
						}
						if(!officUserInstitutionList.contains( targetUserInstitution )){
							officUserInstitutionList.add( targetUserInstitution );
						}
						if(!officUserRoleList.contains( targetUserRole )){
							officUserRoleList.add( targetUserRole );
						}
						if(!officRolesList.contains( targetRoles )){
							officRolesList.add( targetRoles );
						}
						if(!officRoleGroupsList.contains( targetRoleGroups )){
							officRoleGroupsList.add( targetRoleGroups );
						}						
					}
				}

				
				/**
				// 2、机构用户离线数据包：增量升级	
				pusersList = pusersMapper.getInstitutionsPUserListById( institutionId );

				// 3、获取用户详情信息
				if (null != pusersList && pusersList.size() > 0) {
					userIdList = new ArrayList<String>();
					for (Pusers pusers : pusersList) {
						if (!userIdList.contains( pusers.getUserId() )) {
							userIdList.add( pusers.getUserId() );
						}
					}
				}
				userInfosList = userInfosMapper.getUserInfosListByUserIds( userIdList );

				// 4、获取用户机构关系信息数据包：增量升级
				userInstitutionList = userInstitutionMapper.getUserInstitutionsListByInstitutionId( institutionId );

				// 5、获取用户角色关系信息数据包：增量升级
				userRoleList = userRoleMapper.getUserRoleListByUserIdList( userIdList );

				// 6、获取角色关系信息数据包：增量升级
				if (null != userRoleList && userRoleList.size() > 0) {
					roleIdList = new ArrayList<String>();
					for (UserRole userRole : userRoleList) {
						if (!roleIdList.contains( userRole.getRoleId() )) {
							roleIdList.add( userRole.getRoleId() );
						}
					}
				}
				rolesList = rolesMapper.getRolesListByRoleIdList( roleIdList );

				// 7、获取角色组信息数据包：增量升级
				if (null != rolesList && rolesList.size() > 0) {
					roleGroupIdList = new ArrayList<String>();
					for (Roles roles : rolesList) {
						if (!roleGroupIdList.contains( roles.getRoleGroupId() )) {
							roleGroupIdList.add( roles.getRoleGroupId() );
						}

					}
				}
				roleGroupsList = roleGroupsMapper.getRoleGroupListByIds( roleGroupIdList );
				
				**/		

				// 8、获取终端列表离线数据包：全量升级
				terminalsList = terminalsMapper.getTerminalsList();

				// 9、获取IP规则离线数据包：全量升级
				iprulesList = iprulesMapper.getIprulesList( institutionId );

				// 10、获取平台列表离线数据包？？？？：全量升级
				// analysisiByInstitionList =
				// iApplicationsService.getAnalysisiByInstitionList(institutionId);
				// SELECT * FROM dh_applications;
				// SELECT * from dh_appinstitution_relations;
				// SELECT * from dh_institutions;
				// SELECT * from dh_analysis_list;

				AnalysisList analysisList = analysisListService.selectAnalysisiByInstitutionId( institutionId );

				List<Applications> applicationsList = null;
				Applications applications = null;
				List<AppInstitutionRelations> relaByInstitutionIdList = appInstitutionRelationsService
						.getAppInstitutionRelaByInstitutionIdList( institutionId );
				if (null != relaByInstitutionIdList && relaByInstitutionIdList.size() > 0) {
					applicationsList = new ArrayList<Applications>();
					for (AppInstitutionRelations appInstitutionRelations : relaByInstitutionIdList) {
						applications = new Applications();
					/*	applications = iApplicationsService.selectByPrimaryKey( appInstitutionRelations.getAppId() );*/
						if (null != applications) {
							applicationsList.add( applications );
						}
					}
				}

				// 12、获取机构订单离线数据包

				// 12.1通过机构id，获取机构所有订单列表离线数据包：全量升级
				orderNoList = null;
				if (null != orderNoList && orderNoList.size() > 0) {
					orderList = new ArrayList<Orders>();
					// contractsList = new ArrayList<Contract>();
					// invoicesListObj = new ArrayList<Invoices>();
					orderProductsListObj = new ArrayList<OrderProducts>();
					oftenConsigneesList = new ArrayList<OftenConsignees>();
					orderProcessesListObj = new ArrayList<OrderProcesses>();
					resourceCategorysListObj = new ArrayList<ResourceCategors>();
					resourcesListObj = new ArrayList<Resources>();
					resourceRelationsListObj = new ArrayList<ResourceRelations>();
					resCategoryRelationsListObj = new ArrayList<ResCategoryRelations>();
					articleContentsListObj = new ArrayList<ArticleContents>();
					articlesListObj = new ArrayList<Articles>();
					booksListObj = new ArrayList<Books>();
					gamesListObj = new ArrayList<Games>();
					videosListObj = new ArrayList<Videos>();
					magazinesListObj = new ArrayList<Magazines>();
					specialResourceDatasListObj = new ArrayList<SpecialResourceDatas>();
					resourceTypeListObj = new ArrayList<ResourceType>();
					orderCanelReqListObj = new ArrayList<OrderCanelReqVo>();
					orderResourceProductsDetailsListObj = new ArrayList<OrderResourceProductsDetail>();
					orderResoursePriceListObj = new ArrayList<OrderResoursePrice>();
					auditLogsList = new ArrayList<AuditLogs>();
					for (String orderId : orderNoList) {
						orderPublishVo =null;
						if (null != orderPublishVo) {
							orders = orderPublishVo.getOrders();
							if (null != orders) {
								if (!orderList.contains( orders )) {
									orderList.add( orders );
								}
							}

							// contract = orderPublishVo.getContract();
							// if (null != contract) {
							// if (!contractsList.contains( contract )) {
							// contractsList.add( contract );
							// }
							// }

							// invoicesList = orderPublishVo.getInvoicesList();
							// if (null != invoicesList && invoicesList.size() >
							// 0) {
							// for (Invoices invoices : invoicesList) {
							// if (!invoicesListObj.contains( invoices )) {
							// invoicesListObj.add( invoices );
							// }
							// }
							// }
							// 已购买列表
							orderProductsList = orderPublishVo.getOrderProductsList();
							if (null != orderProductsList && orderProductsList.size() > 0) {
								for (OrderProducts orderProducts : orderProductsList) {
									if (!orderProductsListObj.contains( orderProducts )) {
										orderProductsListObj.add( orderProducts );
									}
								}
							}

							// 常用联系人表
							oftenConsignees = orderPublishVo.getOftenConsignees();
							if (null != oftenConsignees) {
								if (!oftenConsigneesList.contains( oftenConsignees )) {
									oftenConsigneesList.add( oftenConsignees );
								}
							}
							// 订单日志列表
							orderProcessesList = orderPublishVo.getOrderProcessesList();
							if (null != orderProcessesList && orderProcessesList.size() > 0) {
								for (OrderProcesses orderProcesses : orderProcessesList) {
									if (!orderProcessesListObj.contains( orderProcesses )) {
										orderProcessesListObj.add( orderProcesses );
									}
								}
							}
							// 资源分类列外表
							resourceCategorysList = orderPublishVo.getResourceCategorysList();
							if (null != resourceCategorysList && resourceCategorysList.size() > 0) {
								for (ResourceCategors resourceCategors : resourceCategorysList) {
									if (null != resourceCategors) {
										if (!resourceCategorysListObj.contains( resourceCategors )) {
											resourceCategorysListObj.add( resourceCategors );
										}
									}

								}
							}

							// 资源
							resourcesList = orderPublishVo.getResourcesList();
							if (null != resourcesList && resourcesList.size() > 0) {
								for (Resources resources : resourcesList) {
									if (null != resources) {
										if (!resourcesListObj.contains( resources )) {
											resourcesListObj.add( resources );
										}
									}
								}
							}

							// 资源关系表
							resourceRelationsList = orderPublishVo.getResourceRelationsList();
							if (null != resourceRelationsList && resourceRelationsList.size() > 0) {
								for (ResourceRelations resourceRelations : resourceRelationsList) {
									if (null != resourceRelations) {
										if (!resourceRelationsListObj.contains( resourceRelations )) {
											resourceRelationsListObj.add( resourceRelations );
										}
									}
								}
							}

							// 资源关系分类
							resCategoryRelationsList = orderPublishVo.getResCategoryRelationsList();
							if (null != resCategoryRelationsList && resCategoryRelationsList.size() > 0) {
								for (ResCategoryRelations resCategoryRelations : resCategoryRelationsList) {
									if (null != resCategoryRelations) {
										if (!resCategoryRelationsListObj.contains( resCategoryRelations )) {
											resCategoryRelationsListObj.add( resCategoryRelations );
										}
									}
								}
							}

							// 文章内容列表
							articleContentsList = orderPublishVo.getArticleContentsList();
							if (null != articleContentsList && articleContentsList.size() > 0) {
								for (ArticleContents articleContents : articleContentsList) {
									if (null != articleContents) {
										if (!articleContentsListObj.contains( articleContents )) {
											articleContentsListObj.add( articleContents );
										}
									}
								}
							}

							// 文章
							articlesList = orderPublishVo.getArticlesList();
							if (null != articlesList && articlesList.size() > 0) {
								for (Articles articles : articlesList) {
									if (null != articles) {
										if (!articlesListObj.contains( articles )) {
											articlesListObj.add( articles );
										}
									}
								}
							}

							// 图书
							booksList = orderPublishVo.getBooksList();
							if (null != booksList && booksList.size() > 0) {
								for (Books books : booksList) {
									if (null != books) {
										if (!booksListObj.contains( books )) {
											booksListObj.add( books );
										}
									}
								}
							}

							// 游戏列表
							gamesList = orderPublishVo.getGamesList();
							if (null != gamesList && gamesList.size() > 0) {
								for (Games games : gamesList) {
									if (null != games) {
										if (!gamesListObj.contains( games )) {
											gamesListObj.add( games );
										}
									}
								}
							}

							// 视频列表
							videosList = orderPublishVo.getVideosList();
							if (null != videosList && videosList.size() > 0) {
								for (Videos videos : videosList) {
									if (null != videos) {
										if (!videosListObj.contains( videos )) {
											videosListObj.add( videos );
										}
									}
								}
							}

							// 杂志列表
							magazinesList = orderPublishVo.getMagazinesList();
							if (null != magazinesList && magazinesList.size() > 0) {
								for (Magazines magazines : magazinesList) {
									if (null != magazines) {
										if (!magazinesListObj.contains( magazines )) {
											magazinesListObj.add( magazines );
										}
									}
								}
							}

							// 终端资源数据列表
							specialResourceDatasList = orderPublishVo.getSpecialResourceDatasList();
							if (null != specialResourceDatasList && specialResourceDatasList.size() > 0) {
								for (SpecialResourceDatas specialResourceDatas : specialResourceDatasList) {
									if (null != specialResourceDatas) {
										if (!specialResourceDatasListObj.contains( specialResourceDatas )) {
											specialResourceDatasListObj.add( specialResourceDatas );
										}
									}
								}
							}

							// 资源类型
							resourceTypeList = orderPublishVo.getResourceTypeList();
							if (null != resourceTypeList && resourceTypeList.size() > 0) {
								for (ResourceType resourceType : resourceTypeList) {
									if (null != resourceType) {
										if (!resourceTypeListObj.contains( resourceType )) {
											resourceTypeListObj.add( resourceType );
										}
									}
								}
							}

							// 订单取消列表
							orderCanelReqList = orderPublishVo.getOrderCanelReqList();
							if (null != orderCanelReqList) {
								if (null != orderCanelReqList) {
									if (!orderCanelReqListObj.contains( orderCanelReqList )) {
										orderCanelReqListObj.add( orderCanelReqList );
									}
								}
							}

							orderResourceProductsDetailsList = orderPublishVo.getOrderResourceProductsDetailsList();
							if (null != orderResourceProductsDetailsList && orderResourceProductsDetailsList.size() > 0) {
								for (OrderResourceProductsDetail orderResourceProductsDetail : orderResourceProductsDetailsList) {
									if (!orderResourceProductsDetailsListObj.contains( orderResourceProductsDetail )) {
										orderResourceProductsDetailsListObj.add( orderResourceProductsDetail );
									}
								}
							}

							orderResoursePriceList = orderPublishVo.getOrderResoursePriceList();
							if (null != orderResoursePriceList && orderResoursePriceList.size() > 0) {
								for (OrderResoursePrice orderResoursePrice : orderResoursePriceList) {
									if (!orderResoursePriceListObj.contains( orderResoursePriceList )) {
										orderResoursePriceListObj.add( orderResoursePrice );
									}
								}
							}
						}

						auditLog = auditLogsService.selectAuditTypeId( orderId );
						if (null != auditLog) {
							if (!auditLogsList.contains( auditLog )) {
								auditLogsList.add( auditLog );
							}
						}
					}
				}
				ExportInstitutionListByIdVo exportInstitutionListByIdVo = new ExportInstitutionListByIdVo();
				exportInstitutionListByIdVo.setInstitutionsList( institutionsList );
				exportInstitutionListByIdVo.setPusersList( officPusersList );
				exportInstitutionListByIdVo.setUserInfosList( officUserInfosList );
				exportInstitutionListByIdVo.setUserInstitutionList( officUserInstitutionList );
				exportInstitutionListByIdVo.setUserRoleList( officUserRoleList );
				exportInstitutionListByIdVo.setRolesList( officRolesList );
				exportInstitutionListByIdVo.setRoleGroupsList( officRoleGroupsList );
				exportInstitutionListByIdVo.setTerminalsList( terminalsList );
				exportInstitutionListByIdVo.setIprulesList( iprulesList );
				// exportInstitutionListByIdVo.setAnalysisiByInstitionList(analysisiByInstitionList);
				exportInstitutionListByIdVo.setAnalysisList( analysisList );
				exportInstitutionListByIdVo.setRelaByInstitutionIdList( relaByInstitutionIdList );
				exportInstitutionListByIdVo.setApplicationsList( applicationsList );
				exportInstitutionListByIdVo.setOrdersList( orderList );
				// exportInstitutionListByIdVo.setContractList( contractsList );
				// exportInstitutionListByIdVo.setInvoicesList( invoicesListObj
				// );
				exportInstitutionListByIdVo.setOrderProductsList( orderProductsListObj );
				exportInstitutionListByIdVo.setOftenConsigneesList( oftenConsigneesList );
				exportInstitutionListByIdVo.setOrderProcessesList( orderProcessesListObj );
				exportInstitutionListByIdVo.setResourceCategorysList( resourceCategorysListObj );
				exportInstitutionListByIdVo.setResourcesList( resourcesListObj );
				exportInstitutionListByIdVo.setResourceRelationsList( resourceRelationsListObj );
				exportInstitutionListByIdVo.setResCategoryRelationsList( resCategoryRelationsListObj );
				exportInstitutionListByIdVo.setArticleContentsList( articleContentsListObj );
				exportInstitutionListByIdVo.setArticlesList( articlesListObj );
				exportInstitutionListByIdVo.setBooksList( booksListObj );
				exportInstitutionListByIdVo.setGamesList( gamesListObj );
				exportInstitutionListByIdVo.setVideosList( videosListObj );
				exportInstitutionListByIdVo.setMagazinesList( magazinesListObj );
				exportInstitutionListByIdVo.setSpecialResourceDatasList( specialResourceDatasListObj );
				exportInstitutionListByIdVo.setResourceTypeList( resourceTypeListObj );
				exportInstitutionListByIdVo.setOrderCanelReqVoList( orderCanelReqListObj );
				exportInstitutionListByIdVo.setOrderResourceProductsDetailsList( orderResourceProductsDetailsListObj );
				exportInstitutionListByIdVo.setOrderResoursePriceList( orderResoursePriceListObj );
				exportInstitutionListByIdVo.setAuditLogsList( auditLogsList );

				filePath = ExportInstitutionList.exportInstitutions( exportInstitutionListByIdVo, institutionId );

				List<OrderPublishVo> oderPulishList = null;
				for (String orderId : orderNoList) {
					oderPulishList = new ArrayList<OrderPublishVo>();
					orderPublishVo = null;
					if (null != orderPublishVo) {
						if (!oderPulishList.contains( orderPublishVo )) {
							oderPulishList.add( orderPublishVo );
						}
					}
				}

				// 异步
				final List<OrderPublishVo> orderPublishVoListfin = oderPulishList;
				// final List<OrderPublishVo>
				// orderPublishVoListfin=exportInstitutionListByIdVo.getOrderPublishVoLists();
				final String institutionIdfin = institutionId;
				Thread thread = new Thread( new Runnable() {
					@Override
					public void run() {
						try {
							if (null != orderPublishVoListfin && orderPublishVoListfin.size() > 0) {
								for (int i = 0; i < orderPublishVoListfin.size(); i++) {
									List<Resources> resourceListfin = orderPublishVoListfin.get( i ).getResourcesList();
									if (null != resourceListfin && resourceListfin.size() > 0) {
										for (int j = 0; j < resourceListfin.size(); j++) {
											Resources resource = resourceListfin.get( j );
											findFileByRes( resource, institutionIdfin );
										}
									}
								}
							}

						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
				} );
				thread.start();

			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return filePath;

	}

	public void findFileByRes(Resources resources, String institutionId) throws Exception {

		ResourceBundle resource = ResourceBundle.getBundle( "application" );
		String staticFilePath = resource.getString( "resourcePath" );

		System.out.println( "file  copy   begin" );
		/*
		 * ChannelSftp sftp = SftpUtil.getSftpConnect("118.31.66.123", 22,
		 * "root", "tsgsq@#018");
		 */
		Institutions institutions = this.institutionsMapper.selectByPrimaryKey( institutionId );
		ResourceType resourceType = this.resourceTypeMapper.selectByPrimaryKey( resources.getResTypeId() );
		if (resourceType != null && institutions != null) {
			String resTable = resourceType.getResTable();
			String resId = resources.getResId();
			Books books;
			Videos videos;
			Games games;
			Magazines magazines;
			String sourchPath = "";

			if (resTable.equals( "Books" )) {
				String beforePath = "";
				String MiddlePath = "updateData/offline/" + ChineseCharToEnUtil.getFullSpell( institutions.getInstitutionName() ) + "/"
						+ DateUtil.getCurDate_YYYY_MM_DD() + "/";
				books = this.iBooksService.selectByPrimaryKey( resId );
				sourchPath = books.getSourcePath() + "/";
				if (StringUtils.isNotBlank( sourchPath )) {
					beforePath = sourchPath.substring( 0, sourchPath.indexOf( "huiben/" ) );
					String str = sourchPath.replace( beforePath, staticFilePath + MiddlePath );

					System.out.println( "bUrl:" + sourchPath + ",eUrl:" + str );
					FileManipulationTool.copyStoreUpdateFolder( sourchPath, str );
				}
			} else if (resTable.equals( "Magazines" )) {
				String beforePath = "";
				String MiddlePath = "updateData/offline/" + ChineseCharToEnUtil.getFullSpell( institutions.getInstitutionName() ) + "/"
						+ DateUtil.getCurDate_YYYY_MM_DD() + "/";
				magazines = this.iMagazinesService.selectByPrimaryKey( resId );
				sourchPath = "" + magazines.getSourcePath();
				if (StringUtils.isNotBlank( sourchPath )) {
					beforePath = sourchPath.substring( 0, sourchPath.indexOf( "password/" ) );
					String newStr = sourchPath.substring( sourchPath.indexOf( "password/" ), sourchPath.indexOf( "pdf/" ) ).replace( "password/",
							"password/main/" )
							+ "web/";

					String str = staticFilePath + MiddlePath + newStr;
					/*
					 * String str=sourchPath.replace(beforePath,
					 * beforePath+MiddlePath);
					 */
					System.out.println( "bUrl:" + sourchPath + ",eUrl:" + str );
					FileManipulationTool.copyStoreUpdateFolder( sourchPath, str );
				}
			} else if (resTable.equals( "Videos" ) || resTable.equals( "Pictures" )) {
				String MiddlePath = "updateData/offline/" + ChineseCharToEnUtil.getFullSpell( institutions.getInstitutionName() ) + "/"
						+ DateUtil.getCurDate_YYYY_MM_DD() + "/";
				videos = this.iVideosService.selectByPrimaryKey( resId );
				sourchPath = "" + videos.getSourcePath() + "/";
				if (StringUtils.isNotBlank( sourchPath )) {
					String rootEnd = sourchPath.substring( sourchPath.indexOf( "videos/" ), sourchPath.length() );
					String targetPath = staticFilePath + MiddlePath + rootEnd;
					File file = new File( sourchPath );
					File[] filelogList = file.listFiles();
					if (null != filelogList && filelogList.length > 0) {
						FileManipulationTool.copyFolder( sourchPath, targetPath );
						for (int k = 0; k < filelogList.length; k++) {
							String fileSuffixVal = filelogList[ k ].getName().substring( filelogList[ k ].getName().lastIndexOf( "." ) + 1 ).trim();
							if (fileSuffixVal.toLowerCase().equals( "mp4" ) || fileSuffixVal.toLowerCase().equals( "flv" )
									|| fileSuffixVal.toLowerCase().equals( "mpg" ) || fileSuffixVal.toLowerCase().equals( "jpg" )
									|| fileSuffixVal.toLowerCase().equals( "jpeg" ) || fileSuffixVal.toLowerCase().equals( "png" )
									|| fileSuffixVal.toLowerCase().equals( "bmp" ) || fileSuffixVal.toLowerCase().equals( "gif" )) {
								System.out.println( "bUrl:" + sourchPath + filelogList[ k ].getName() + ",eUrl:" + targetPath
										+ filelogList[ k ].getName() );
								VideoCopyFileUtils.videoCopyFile( sourchPath + filelogList[ k ].getName(), targetPath + filelogList[ k ].getName() );
							}
						}

					}

				}

			}

		}

	}

	/**
	 * 复制一个目录及其子目录、文件到另外一个目录
	 * 
	 * @param src
	 * @param dest
	 * @throws IOException
	 */
	private void copyFolder(File src, File dest) throws IOException {
		if (src.isDirectory()) {
			if (!dest.exists()) {
				dest.mkdir();
			}
			String files[] = src.list();
			for (String file : files) {
				File srcFile = new File( src, file );
				File destFile = new File( dest, file );
				// 递归复制
				copyFolder( srcFile, destFile );
			}
		} else {
			InputStream in = new FileInputStream( src );
			OutputStream out = new FileOutputStream( dest );

			byte[] buffer = new byte[1024];

			int length;

			while ((length = in.read( buffer )) > 0) {
				out.write( buffer, 0, length );
			}
			in.close();
			out.close();
		}
	}

	public static void main(String[] str) {
		/* */

		String ss = "/usr/local/tomcatThree/webapps/StaticServer/upload/image/storage_test/static.61read.com/videos/feizhoudongwu/pictures/dongwubaike/heibeimaiji/";

		String MiddlePath = "updateData/offline/" + ChineseCharToEnUtil.getFullSpell( "第三方第三方" ) + "/" + DateUtil.getCurDate_YYYY_MM_DD() + "/";

		String sourchPath = ss + "/";
		if (StringUtils.isNotBlank( sourchPath )) {
			String rootEnd = sourchPath.substring( sourchPath.indexOf( "videos/" ), sourchPath.length() );
			String targetPath = "/usr/local/tomcatThree/webapps/StaticServer/upload/image/storage_test/" + MiddlePath + rootEnd;
			System.out.println( targetPath );
		}
	}

	/**
	 * 通过机构id查询所属机构信息.
	 * 
	 * @param institutionId
	 * @return
	 */
	@Override
	public InstitutionsInfoVo getParentInstitutionsById(String institutionId) {
		return institutionsMapper.getParentInstitutionsById( institutionId );
	}

	/**
	 * 查询子机构分页查询
	 * 
	 * @param institutionId
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@Override
	public PagedResult<Institutions> selectSublevelInstitutionsList(TreeQueryVo treeQueryVo) {
		Integer pageNo = treeQueryVo.getPageNumber() == null ? 1 : treeQueryVo.getPageNumber();
		Integer pageSize = treeQueryVo.getPageSize() == null ? 10 : treeQueryVo.getPageSize();
		// startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		PageHelper.startPage( pageNo, pageSize );
		return BeanUtils.toPagedResult( institutionsMapper.selectSublevelInstitutionsList( treeQueryVo ) );
	}

	/**
	 * 带条件查询机构列表
	 */
	@Override
	public PagedResult<QueryInstitutionsVo> selectInstitutionsCountList(InstitutionsVo institutionsCountVo, Integer pageNo, Integer pageSize) {
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? 10 : pageSize;
		// startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		PageHelper.startPage( pageNo, pageSize );
		return BeanUtils.toPagedResult( institutionsMapper.selectInstitutionsCountList( institutionsCountVo ) );
	}

	/**
	 * 通过userid查询机构信息.
	 */
	@Override
	public List<Institutions> getInstitutionsByUserId(String userId) {
		return institutionsMapper.getInstitutionsListByUserId( userId );
	}

	/**
	 * 获取机构总数.
	 * 
	 * @return
	 */
	@Override
	public Integer getInstitutionsCount() {
		return institutionsMapper.getInstitutionsCount();
	}

	/**
	 * 通过机构id查询子机构列表信息.
	 * 
	 * @param institutionId
	 * @return
	 */
	@Override
	public List<Institutions> getSublevelInstitutionsList(String institutionId) {
		return institutionsMapper.getSublevelInstitutionsList( institutionId );
	}

	/**
	 * 获取子机构总数.
	 * 
	 * @param institutionId
	 * @return
	 */
	@Override
	public Integer getSublevelInstitutionsListSize(TreeQueryVo treeQueryVo) {
		return institutionsMapper.getSublevelInstitutionsListSize( treeQueryVo );
	}

	/**
	 * 修改用户详情及机构、用户信息操作.
	 */
	@Override
	public int updateInstitutionsInfo(Institutions institutions) {
		int result = 0;
		result += institutionsMapper.updateByPrimaryKeySelective( institutions );
		List<InstitutionsListVo> institutionsListVo = null;
		institutionsListVo = InstitutionsMongo.findInstitutionsAll( new HashMap<String, Object>() );
		if (null != institutionsListVo && institutionsListVo.size() > 0) {
			// 先删除mongo数据
			InstitutionsMongo.deleteInstitutionsAll();
		}
		institutionsListVo = institutionsMapper.getInstitutionsList();
		if (null != institutionsListVo && institutionsListVo.size() > 0) {
			// 存储mogoDb
			InstitutionsMongo.addInstitutions( institutionsListVo );
		}
		return result;
	}

	/**
	 * 通过机构名称查询机构信息.
	 * 
	 * @param institutionName
	 * @return
	 */
	@Override
	public Institutions selectInstitutionsByName(String institutionName) {
		return institutionsMapper.selectInstitutionsByName( institutionName );
	}

	/**
	 * 获取机构上\下级级联关系列表.
	 * 
	 * @return
	 */
	@Override
	public List<InstitutionsListVo> getInstitutionsList() {
		List<InstitutionsListVo> institutionsListVo = null;
		institutionsListVo = InstitutionsMongo.findInstitutionsAll( new HashMap<String, Object>() );
		if (institutionsListVo == null || institutionsListVo.isEmpty()) {
			institutionsListVo = institutionsMapper.getInstitutionsList();
			if (null != institutionsListVo && institutionsListVo.size() > 0) {
				// 存储mogoDb
				InstitutionsMongo.addInstitutions( institutionsListVo );
			}
		}
		return institutionsListVo;
	}

	/**
	 * 批量删除机构信息.
	 */
	@Override
	public int deleteInstitutionsByIdBatch(List<String> institutionIdList) throws Exception {
		int result = 0;
		if (null != institutionIdList && institutionIdList.size() > 0) {
			List<String> userIdList = null;
			for (String institutionsId : institutionIdList) {
				// 清理机构用户
				List<Pusers> pusersList = pusersMapper.getInstitutionsPUserListById( institutionsId );
				if (null != pusersList && pusersList.size() > 0) {
					userIdList = new ArrayList<String>();
					for (Pusers pusers : pusersList) {
						if (!userIdList.contains( pusers.getUserId() )) {
							userIdList.add( pusers.getUserId() );
						}
					}
					// 删除用户
					pusersMapper.deletePusersByIdBatch( userIdList );
					// 删除用户详情
					userInfosMapper.deleteByUserInfosByIdBatch( userIdList );
					// 删除用户角色关系
					userRoleMapper.deleteUserRoleInfoByUserId( userIdList );

					// 删除用户机构关系
					userInstitutionMapper.deleteBatchUserInstitution( userIdList );
				}

				// 清理机构ip白名单
				List<Iprules> iprulesList = iprulesMapper.getIprulesList( institutionsId );
				if (null != iprulesList && iprulesList.size() > 0) {
					for (Iprules iprules : iprulesList) {
						iprulesMapper.deleteByPrimaryKey( iprules.getIpRuleId() );
					}
				}

				// 清理机构应用管理
				/*List<Applications> applicationsList = iApplicationsService.getApplicationListByInstitutionId( institutionsId );
				if (null != applicationsList && applicationsList.size() > 0) {
					for (Applications applications : applicationsList) {
						iApplicationsService.deleteByPrimaryKey( applications.getAppId() );
					}
				}*/
				result += institutionsMapper.deleteByPrimaryKey( institutionsId );
				List<InstitutionsListVo> institutionsListVo = null;
				institutionsListVo = InstitutionsMongo.findInstitutionsAll( new HashMap<String, Object>() );
				if (null != institutionsListVo && institutionsListVo.size() > 0) {
					// 先删除mongo数据
					InstitutionsMongo.deleteInstitutionsAll();
				}
				institutionsListVo = institutionsMapper.getInstitutionsList();
				if (null != institutionsListVo && institutionsListVo.size() > 0) {
					// 存储mogoDb
					InstitutionsMongo.addInstitutions( institutionsListVo );
				}
			}
		}
		// return
		// institutionsMapper.deleteInstitutionsByIdBatch(institutionIdList);
		return result;
	}

	/**
	 * 批量启用，禁用机构.
	 * 
	 * @param institutionMap
	 * @return
	 */
	@Override
	public int batchUpdateInstitutionsWithMap(List<StatusList> list) {
		return institutionsMapper.batchUpdateInstitutionsWithMap( list );
	}

	@Override
	public String getInstitutionsId(String institutionId) {
		return institutionsMapper.getInstitutionsId( institutionId );
	}

	@Override
	public Institutions getInstitutionsById(String userId) {
		return institutionsMapper.getInstitutionsById( userId );
	}

	/**
	 * 通过机构id查询子级、所有子级、遍历至最上级根目录Tree机构树形.
	 * 
	 * @param institutionId
	 * @return
	 */
	@Override
	public Set<String> getPublishInstitutionsTreeList(String institutionId) {
		Set<String> institutionIdSet = null;
		List<Institutions> sublevelInstitutionsList = null;
		if (StringUtils.isNotBlank( institutionId )) {
			institutionIdSet = new HashSet<String>();
			sublevelInstitutionsList = institutionsMapper.getPublishInstitutionsTreeList( institutionId );
			if (null != sublevelInstitutionsList && sublevelInstitutionsList.size() > 0) {
				for (Institutions institutionVal : sublevelInstitutionsList) {
					if (!institutionIdSet.contains( institutionVal.getInstitutionId() )) {
						institutionIdSet.add( institutionVal.getInstitutionId() );
					}
				}
			}
		}

		Institutions institutions = institutionsMapper.selectByPrimaryKey( institutionId );
		if (null != institutions) {
			institutionIdSet = getParentId( institutionIdSet, institutions.getParentId() );
		}
		return institutionIdSet;
	}

	/**
	 * 内部方法递归求所有上级的机构id.
	 * 
	 * @param institutionIdSet
	 * @param institutionId
	 * @return
	 */
	private Set<String> getParentId(Set<String> institutionIdSet, String institutionId) {
		Institutions institutions = null;
		while (!institutionId.equals( "0" )) {
			institutions = institutionsMapper.selectByPrimaryKey( institutionId );
			if (null != institutions) {
				if (!institutionIdSet.contains( institutions.getInstitutionId() )) {
					institutionIdSet.add( institutions.getInstitutionId() );
				}
			}
			institutionId = institutions.getParentId();
			getParentId( institutionIdSet, institutionId );
		}

		return institutionIdSet;
	}

	/**
	 * 通过父级机构id获取子级最大的到期日期.
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public String getSublevelInstitutionsMaxVaildDate(String id) {
		return institutionsMapper.getSublevelInstitutionsMaxVaildDate( id );
	}

	@Override
	public List<Institutions> selectInstitutionsList() {
		return institutionsMapper.selectInstitutionsList();
	}

	public void test() {
		try {
			Resources resources = this.resourcesMapper.selectByPrimaryKey( "011cd4177b56e58bc85953d3b40acff1" );
			findFileByRes( resources, "0d01c9716381485291080cb3bbd9eb28" );
		} catch (Exception ex) {
			System.out.println( ex.toString() );
		}

	}

	public List<String> getAllInstitutions(String institutionId, List<String> InstitutionsStringList) {
		InstitutionsStringList.add( institutionId );
		List<Institutions> InstitutionsList = this.getSublevelInstitutionsList( institutionId );
		if (null != InstitutionsList && InstitutionsList.size() > 0) {
			for (int i = 0; i < InstitutionsList.size(); i++) {
				/*
				 * if(InstitutionsList.get( i ).getParentId().equals(
				 * InstitutionsList )||InstitutionsList.get( i
				 * ).getInstitutionId().equals( institutionId )) {
				 */
				if (!InstitutionsStringList.contains( InstitutionsList.get( i ).getInstitutionId() )) {
					InstitutionsStringList = getAllInstitutions( InstitutionsList.get( i ).getInstitutionId(), InstitutionsStringList );
				}
				/* } */
			}
		}
		return InstitutionsStringList;

	}
}